<template>
    <div class="app-container">
      <div v-show="!detailInfo.visible && !modifyInfo.visible && !assetDetailInfo.visible">
        <!-- 条件栏 -->
        <div class="filter-wrapper">
          <NewPageFilter
            v-model:query="filterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="filterInfo.searchList"
            :filter-btn="filterInfo.searchBtn"
            :clear-type="clearType"
            :slip-select-request="slipSelectRequest"
          >
          <template v-slot:filter-useDeptName>
            <slip-select
              v-model="filterInfo.query.queryParams.useDeptIdMult"
              value-key="value"
              placeholder="选择使用部门"
              :api="inOrOutDepotInfo.api"
              key-field="name"
              value-field="id"
              v-model:query="inOrOutDepotInfo.query"
              :clearable="true"
              :filterable="true"
              :multiple="true"
              @change="search"
            />
          </template>
          </NewPageFilter>
        </div>
        <div class="filter-wrapper">
          <NewPageFilter :filter-btn="filterInfo.btnList">
            <template v-slot:filter-print>
              <!-- <el-button @click="print()">打印</el-button> -->
              <PopoverPrint
                ref="popoverShow"
                v-model:popoverVisible="popoverVisible"
                :canPrint="true"
                :templateArr="templateArr"
                @tempClick="tempClick"
                @print="print"
              ></PopoverPrint>
            </template>
            <template v-slot:filter-download>
              <el-button @click="exportExcel()">导出excel</el-button>
            </template>
          </NewPageFilter>
          <div class="display-flex">
            <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
          </div>
        </div>
        <!-- 表格 -->
        <table-container
          :refresh="tableInfo.refresh"
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :api="tableInfo.api"
          :check-box="false"
          :tab-index="true"
          :query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          :row-class-name="tableRowClassName"
          @sortChange="sortChange"
          @handleEvent="handleEvent"
          @pageInfo="pageInfo"
        >
          <template v-slot:col-assetName="scope">
            <span class="slip-edit" @click="showAssetDetail(scope.row)">{{
              scope.row.assetName
            }}</span>
          </template>
          <template v-slot:col-age="scope">
            <span>{{scope.row.age == -2 ? '-' : scope.row.age }}</span>
          </template>
          <template v-slot:col-remindDuration="scope">
            <span
              >{{ scope.row.remindDuration || 0 }}
              {{ scope.row.remindTimeTypeValue || '-' }}</span
            >
          </template>
        </table-container>
      </div>
      <order-detail
        v-if="detailInfo.visible"
        v-model:visible="detailInfo.visible"
        :table-row-id="detailInfo.id"
        title="设备启停详情"
        @returnBack="getList"
      />
      <set-preference
        v-if="preferenceInfo.visible"
        v-model:visible="preferenceInfo.visible"
        :search-list="filterInfo.searchList"
        :field-list="tableInfo.fieldList"
        :customize-user-v-o="filterInfo.query.customizeUserVO"
        :group-level-show="false"
        @callback="setPreferenceCallback"
      />
      <advanced-search
        v-if="advancedSearchInfo.visible"
        v-model:visible="advancedSearchInfo.visible"
        v-model:form-data="advancedSearchInfo.data"
        :field-list="tableInfo.fieldList"
        @callback="advancedSearchCallback"
      />
      <OrderModify
        v-if="modifyInfo.visible"
        :id="modifyInfo.id"
        v-model:visible="modifyInfo.visible"
        :title="modifyInfo.title"
        @returnModify="returnModify"
      />
      <enable
        v-if="enableInfo.visible"
        :data="enableInfo.data"
        v-model:visible="enableInfo.visible"
        :title="enableInfo.title"
        @callback="returnModify"
      />
      <disable
        v-if="disableInfo.visible"
        :data="disableInfo.data"
        v-model:visible="disableInfo.visible"
        :title="disableInfo.title"
        @callback="returnModify"
      />
      <page-dialog
        v-if="dialogTipsInfo.visible"
        :title="dialogTipsInfo.title"
        v-model:visible="dialogTipsInfo.visible"
        :width="dialogTipsInfo.width"
        :bt-loading="dialogTipsInfo.btLoading"
        :bt-list="dialogTipsInfo.btList"
      >
        <div class="asset-msg">
          <div class="asset-msg-label">
            <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
          </div>
          <el-radio-group v-model="dialogTipsInfo.flag">
            <el-radio :label="true">当前页数据</el-radio>
            <el-radio :label="false">全部页数据</el-radio>
          </el-radio-group>
        </div>
      </page-dialog>
      <asset-card-detail
        v-if="assetDetailInfo.visible"
        :id="assetDetailInfo.id"
        v-model:visible="assetDetailInfo.visible"
        :title="assetDetailInfo.title"
      />
    </div>
  </template>
  
  <script setup name="equipmentUpDown">
  import TableContainer from '@/components/TableContainer/index'
  import {
    getUseManagePage,
    deleteUseManagePage,
    canalUseManage,
    exportUseManage,
    printUseManage,
  } from '@/api/asset.js'
  import { fatchTemplateByCode } from '@/api/base.js'
  import OrderDetail from './details'
  import OrderModify from './modify'
  import enable from './components/enable.vue'
  import disable from './components/disable.vue'
  import PageDialog from '@/components/PageDialog/index'
  import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
  import { getDepotAll, getDeptAll } from '@/api/core'
  import { selectByCodeAndDept } from "@/api/report.js";
  import { doPrint } from "@/utils/exportUtil.js";

  const { proxy } = getCurrentInstance()
  const emit = defineEmits()
  
  const SetPreference = defineAsyncComponent(() =>
    import('@/components/SetPreference/index')
  )
  const AdvancedSearch = defineAsyncComponent(() =>
    import('@/components/AdvancedSearch/index')
  )

  const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const inOrOutDepotInfo = reactive({
  api: getDeptAll,
  query: {
    deptAuth: 'id',
    status: 1,
  },
})
  const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
  
  const dialogTipsInfo = reactive({
    visible: false,
    title: '提示',
    btLoading: false,
    type: '',
    msg: '',
    width: '400px',
    flag: true,
    btList: [
      { label: '关闭', event: handleClose, show: true },
      {
        label: '打印',
        type: 'primary',
        event: checkConfirm,
        show: true,
      },
    ],
  })
  // 过滤相关配置
  const filterInfo = reactive({
    sortArr: [],
    copyQueryMap: {},
    query: {
      sortString: '',
      customizeUserVO: {},
      queryMap: {
      },
      queryParams:{
        useDeptIdMult: ''
      },
    },
    searchList: [],
    searchBtn: [
      { type: 'button', label: '搜索', event: search },
      { type: 'button', label: '高级查询', event: advancedSearchShow },
      { type: 'button', label: '重置', event: clearSearch },
    ],
    btnList: [
      {
        type: 'button',
        label: '新增',
        event: create,
        show: proxy.$permission('equipmentUpDown:add'),
      },
      {
        type: 'slot',
        value: 'download',
        show: proxy.$permission('equipmentUpDown:excel'),
      },
      {
        type: 'slot',
        value: 'print',
        show: proxy.$permission('equipmentUpDown:print'),
      },
    ],
  })
  // 表格相关
  const tableInfo = reactive({
    refresh: 1,
    initCurpage: 1,
    data: [],
    api: undefined,
    selections: [],
    fieldList: [],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '100',
      btList: [
        // 1 待启动  2 带停止  3 已停止  4 已作废
        {
          label: '详情',
          event: showDetail,
          show: true
        },
        {
          label: '修改',
          event: update,
          show: proxy.$permission('equipmentUpDown:update'),
          ifRender: function (row) {
            return row.status === 1
          },
        },
        {
          label: '删除',
          event: handDelete,
          show: proxy.$permission('equipmentUpDown:delete'),
          ifRender: function (row) {
            return row.status === 1
          },
        },
        {
          label: '启动',
          event: chenckPlanEnabled,
          show: proxy.$permission('equipmentUpDown:start'),
          ifRender: function (row) {
            return row.status == 1
          },
        },
        {
          label: '停止',
          event: checkPlanDisabled,
          show: proxy.$permission('equipmentUpDown:stop'),
          ifRender: function (row) {
            return row.status == 2
          },
        },
        {
          label: '作废',
          event: checkcanalUseManage,
          show: proxy.$permission('equipmentUpDown:cancle'),
          ifRender: function (row) {
            return row.status == 3
          },
        },
      ],
    },
  })
  
  const detailInfo = reactive({
    visible: false,
    id: '',
  })
  const modifyInfo = reactive({
    visible: false,
    id: '',
    title: '',
  })
  const enableInfo = ref({
    visible: false,
    id: '',
    title: '',
    data:{}
  })
  const disableInfo = ref({
    visible: false,
    id: '',
    title: '',
    data:{}
  })
  
  const preferenceInfo = reactive({
    visible: false,
  })
  const advancedSearchInfo = reactive({
    visible: false,
    data: {},
  })
  let page = ref({
    curPage: 1, // 当前页
    pageSize: 20, // 每页条数
  })
  const clearType = ref(true)
  const slipSelectRequest = ref(true)
  const templateArr = ref([]);
  const popoverVisible = ref(false);
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_use_manage_type',
      show: false,
      hidden: true,
    },
    remindDuration: {
      label: '提醒时长',
      value: 'remindDuration',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    age: {
      label: '年龄',
      value: 'age',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    planStatusValue: {
      label: '生效状态',
      value: 'planStatusValue',
      asValue: 'planStatus',
      componentType: 'select-model',
      code: 'patrol_plan_order_kind',
      show: false,
      hidden: true,
    },
    depotName: {
      label: '出库仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    useDeptName: {
      label: '使用部门',
      value: 'useDeptName',
      asValue: 'useDeptId',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      show: false,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      console.log(val, 'toPage.value')
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'equipmentUpDown' && el.url === val.url) {
                detailInfo.visible = false
                modifyInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})


  
  function chenckPlanEnabled(row) {
    enableInfo.value.visible = true
    enableInfo.value.title = '设备启动'
    enableInfo.value.data = row
  }
  function checkPlanDisabled(row) {
    disableInfo.value.visible = true
    disableInfo.value.title = '设备停用'
    disableInfo.value.data = row
  }
  function checkcanalUseManage(row) {
    canalUseManage(row).then((res) => {
      if (res.success && res) {
        getList()
      }
    })
  }
  function create() {
    modifyInfo.visible = true
    modifyInfo.id = ''
    modifyInfo.title = '新增设备启停'
  }
  function update(row) {
    sessionStorage.setItem('storeRowId', row.id)
    modifyInfo.visible = true
    modifyInfo.id = row.id
    modifyInfo.title = '修改设备启停'
  }
  function handDelete(row) {
    proxy
    .$confirm(
      '是否确认删除?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      deleteUseManagePage([row.id])
        .then((res) => {
          if (res.success) {
            getList()
            showTip('删除成功')
          }
        })
        .catch((err) => {})
    })
    .catch(() => {})
  }
  function returnModify() {
    if (modifyInfo.id) {
      getList()
    } else {
      search()
    }
  }
  async function setPreferenceCallback(obj) {
    updateUserCustomize(obj.customizeUserVO).then((res) => {
      if (res && res.success) {
        getCustomize(!slipSelectRequest.value)
      }
    })
  }
  function pageInfo(obj) {
    page.value = obj
  }
  function handleClose() {
    dialogTipsInfo.visible = false
  }
  function checkConfirm() {
    if (dialogTipsInfo.type === 'excel') {
      exportExcelList()
    } else if (dialogTipsInfo.type === 'print') {
      printList()
    }
    dialogTipsInfo.visible = false
    dialogTipsInfo.msg = ''
  }
  function exportExcel() {
    //导出
    dialogTipsInfo.visible = true
    dialogTipsInfo.type = 'excel'
    dialogTipsInfo.msg = '请选择数据导出范围'
    dialogTipsInfo.btList[1].label = '导出'
    dialogTipsInfo.flag = true
  }
  function exportExcelList() {
    let params = {
      ...filterInfo.query,
      ...page.value,
      page: dialogTipsInfo.flag,
    }
    exportUseManage(params).then((resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    })
  }
  function print() {
    //打印
    dialogTipsInfo.visible = true
    dialogTipsInfo.type = 'print'
    dialogTipsInfo.msg = '请选择当数据打印范围'
    dialogTipsInfo.btList[1].label = '打印'
    dialogTipsInfo.flag = true
  }
  function printList() {
    selectByCodeAndDept({
    tempCode: "assetUseManageList",
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data;
      popoverVisible.value = true;
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        console.log(proxy.$refs.popoverShow);
        proxy.$refs.popoverShow.hidePopover();
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.query,
              ...page.value,
              page: dialogTipsInfo.flag
            }),
          },
        });
      }
    }
  });
  }
  function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      ...filterInfo.value.query,
    },
    callback: printCallback,
    data: {},
  });
  popoverVisible.value = false;
}

function printCallback() {
  try {
    // 打印成功增加打印次数
    // updatePrintCount({
    //   orderNo: infoList.value.data.orderNo,
    //   orderId: props.orderId,
    //   tempCode: 'paymentDeatil',
    //   orderType: 0,
    // })
  } catch (error) {}
}

  
  function advancedSearchShow() {
    advancedSearchInfo.visible = true
  }
  async function advancedSearchCallback(obj) {
    filterInfo.query.queryMap = {}
    filterInfo.query.queryDtoList = [...obj.queryDtoList]
    advancedSearchInfo.data = obj.data
    await getList()
    clearType.value = !clearType.value
    filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  }
  // 获取列表
  async function getList() {
    tableInfo.refresh = Math.random()
  }
  // 搜索
  function search() {
    // 重置分页
    advancedSearchInfo.data = {}
    filterInfo.query.queryDtoList = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  }
  
  //展示明细
  function showDetail(row) {
    sessionStorage.setItem('storeRowId', row.id)
    detailInfo.id = row.id
    detailInfo.visible = true
  }
  function showAssetDetail(row) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
  function tableRowClassName({ row }) {
    let rowId = sessionStorage.getItem('storeRowId')
    if (rowId && row.id === Number(rowId)) {
      return 'check-row'
    }
    return ''
  }
  // 触发事件
  function handleEvent(event, data) {
    switch (event) {
      case 'tableCheck':
        tableInfo.selections = [...data]
        break
    }
  }
  function clearSearch() {
    clearType.value = !clearType.value
    advancedSearchInfo.data = {}
    filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
    filterInfo.query.queryParams.useDeptIdMult = ''
    search()
  }
  function getCustomize(_slipSelectRequest = true) {
    let param = {
      tableKey:
        'assetUseManageList-com.slip.spd.entity.vo.asset.AssetUseManageVO',
    }
    getCustomizeSetting(param).then((res) => {
      if (res && res.success) {
        let data = res.data
        filterInfo.query.customizeUserVO = data
        tableInfo.fieldList = proxy.$fn.setFieldList(
          tableInfo.fieldList,
          data.detail
        )
        let searchInfo = proxy.$fn.setSearchList(
          filterInfo.searchList,
          data.detail
        )
        filterInfo.query.queryMap = {
          ...searchInfo.queryMap,
          ...filterInfo.query.queryMap,
        }
        filterInfo.searchList = [
          ...searchInfo.searchList,
          {
            slot: true,
            value: 'useDeptName',
          }
        ]
        filterInfo.searchList.forEach((item) => {
          item.event = search
        })
        filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
        slipSelectRequest.value = _slipSelectRequest
        tableInfo.api = getUseManagePage
        getList()
      }
    })
  }
  function sortChange(column) {
    if (filterInfo.query.customizeUserVO.head.sortType === 0) {
      let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
      filterInfo.sortArr = arr
      filterInfo.query.sortString = arr.length ? arr.toString() : ''
      getList()
    }
  }
  </script>
  
  <style scoped lang="scss">
  .dialogInfo-form-title {
    width: 100%;
    padding-left: 10px;
    color: #6dc1a9;
    margin-bottom: 20px;
    span {
      color: rgb(95, 91, 91);
      font-size: 12px;
    }
  }
  </style>
  